package com.jinsilu.freight.ui.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jinsilu.freight.R;
import com.jinsilu.freight.aop.Permissions;
import com.jinsilu.freight.aop.SingleClick;
import com.jinsilu.freight.common.MyFragment;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.request.AdCountApi;
import com.jinsilu.freight.http.request.BannerApi;
import com.jinsilu.freight.http.request.BlankNoteRemainApi;
import com.jinsilu.freight.http.request.GetNoticeListApi;
import com.jinsilu.freight.http.response.NoticeBean;
import com.jinsilu.freight.http.response.UserInfoBean;
import com.jinsilu.freight.other.AppConfig;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.activity.BrowserActivity;
import com.jinsilu.freight.ui.activity.HomeActivity;
import com.jinsilu.freight.ui.activity.ManageAccountActivity;
import com.jinsilu.freight.ui.activity.MyVehicleManageActivity;
import com.jinsilu.freight.ui.activity.ScanOrderListActivity;
import com.jinsilu.freight.ui.activity.SourceMallDetailsActivity;
import com.jinsilu.freight.ui.activity.SuggestionsActivity;
import com.jinsilu.freight.ui.activity.SuggestionsListActivity;
import com.jinsilu.freight.ui.activity.ZXLCaptureActivity;
import com.jinsilu.freight.http.response.ADBean;
import com.jinsilu.freight.ui.banner.BannerBean;
import com.jinsilu.freight.ui.banner.ImageAdapter;
import com.jinsilu.freight.ui.banner.TopLineAdapter;
import com.king.zxing.CameraScan;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.youth.banner.Banner;
import com.youth.banner.transformer.ZoomOutPageTransformer;
import com.youth.banner.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * author : byd
 * time   : 2020年11月6日
 * desc   : 网络货运首页
 */
public final class HomeFragment extends MyFragment<HomeActivity> {

    private Banner mHomeBanner;
    private Banner mMessageBanner;
    private TextView mCurrentVehicle;
    private TextView mHomeMoreMessage;
    private TextView mTvNotice;

    private TextView mTvBlankNoteRemain;
    private TextView mTvGoUseBlankNote;

    private LinearLayout mLlIsShowBlankNote;

    // 消息通知
    private List<BannerBean> mNotices;

    private static final int CODE_SELECT_IMAGE = 1;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment;
    }

    @Override
    protected void initView() {
        mHomeBanner = findViewById(R.id.home_banner);
        mMessageBanner = findViewById(R.id.message_banner);
        mCurrentVehicle = findViewById(R.id.home_tv_current_vehicle);
        mHomeMoreMessage = findViewById(R.id.home_tv_more_message);

        mTvNotice = findViewById(R.id.tv_notice);

        mTvBlankNoteRemain = findViewById(R.id.tv_blank_note_remain);
        mTvGoUseBlankNote = findViewById(R.id.tv_go_use_blank_note);

        mLlIsShowBlankNote = findViewById(R.id.ll_is_show_blank_note);

        setOnClickListener(R.id.ll_home_vehicle, R.id.ll_home_scan,
                R.id.home_tv_more_message, R.id.me_ll_account_manage,
                R.id.me_ll_contact_customer, R.id.me_ll_complaint,
                R.id.me_ll_help_center, R.id.tv_go_use_blank_note,
                R.id.iv_go_oil_gas, R.id.iv_go_shop_mall);

        if (CommonHelper.isShowBlankNote()) {
            mLlIsShowBlankNote.setVisibility(View.VISIBLE);
        } else {
            mLlIsShowBlankNote.setVisibility(View.GONE);
        }
        mLlIsShowBlankNote.setVisibility(View.GONE);

        initLocalBaner();
    }


    private void initLocalBaner(){
        List<ADBean> local = new ArrayList<>();
        ADBean adBean = new ADBean();
        adBean.setImageRes(R.drawable.banner1);
        local.add(adBean);
        ADBean adBean2 = new ADBean();
        adBean2.setImageRes(R.drawable.banner2);
        local.add(adBean2);
        ADBean adBean3 = new ADBean();
        adBean3.setImageRes(R.drawable.banner3);
        local.add(adBean3);
        ADBean adBean4 = new ADBean();
        adBean4.setImageRes(R.drawable.banner4);
        local.add(adBean4);
        ADBean adBean5 = new ADBean();
        adBean5.setImageRes(R.drawable.banner5);
        local.add(adBean5);


        initHomeBanner(local);
    }

    @Override
    protected void initData() {
//        initHomeBanner();
//        initMessageBanner();
    }

    @Override
    public void onResume() {
        super.onResume();
//        getBannerList();
//        getNoticeList();
//        getBlankNoteRemain();
    }

    private void getBlankNoteRemain() {
//         获取白条剩余额度
        EasyHttp.get(this)
                .api(new BlankNoteRemainApi())
                .request(new HttpCallback<HttpData<String>>(this) {
                    @Override
                    public void onSucceed(HttpData<String> data) {
                        /*
                         * 司机有白条额度的使用显示：您有XXX的白条额度——去使用。点击去使用的时候跳转到卡车宝贝小程序
                         * 司机没有白条额度的时候显示：开通白条额度，享受更多优惠
                         */
                        if (!TextUtils.isEmpty(data.getData()) && Float.parseFloat(data.getData()) > 0) {
                            mTvGoUseBlankNote.setVisibility(View.VISIBLE);
                            mTvBlankNoteRemain.setText(String.format("您有%s元的白条额度", TextUtils.isEmpty(data.getData()) ? "0.00" : data.getData()));
                        } else {
                            mTvGoUseBlankNote.setVisibility(View.GONE);
                            mTvBlankNoteRemain.setText("开通白条额度，享受更多优惠");
                        }
                    }
                });
    }

    public void setUserCar() {
        UserInfoBean userInfoBean = (UserInfoBean) CommonHelper.getSavedObject("userInfo", UserInfoBean.class);
        if (!ObjectUtils.isEmpty(userInfoBean) && !TextUtils.isEmpty(userInfoBean.getVehicleNumber())) {
            if (null != mCurrentVehicle)
                mCurrentVehicle.setText(userInfoBean.getVehicleNumber());
        } else {
            if (null != mCurrentVehicle)
                mCurrentVehicle.setText("暂无");
        }
    }

    private void initMessageBanner() {
        //实现1号店和淘宝头条类似的效果
        mNotices = new ArrayList<>();
        mMessageBanner.setAdapter(new TopLineAdapter(mNotices))
                .setOrientation(Banner.VERTICAL)
                .setPageTransformer(new ZoomOutPageTransformer())
                .setOnBannerListener((data, position) -> {
                    LogUtils.i(((BannerBean) data).title);
                });
    }

    private void getBannerList() {
        // 获取Banner
        EasyHttp.get(this)
                .api(new BannerApi())
                .request(new HttpCallback<HttpData<List<ADBean>>>(this) {

                    @Override
                    public void onSucceed(HttpData<List<ADBean>> data) {
                        initHomeBanner(data.getData());
                    }
                });
    }

    private void getClickCount(String id) {
        // 统计广告点击数量
        EasyHttp.get(this)
                .api(new AdCountApi().setId(id))
                .request(new HttpCallback<HttpData<String>>(this) {

                    @Override
                    public void onSucceed(HttpData<String> data) {
                        LogUtils.e(data.getData());
                    }
                });
    }

    private void getNoticeList() {
        // 消息通知（只显示最新一条 @wyh）
        EasyHttp.get(this)
                .api(new GetNoticeListApi())
                .request(new HttpCallback<HttpData<NoticeBean>>(this) {
                    @Override
                    public void onSucceed(HttpData<NoticeBean> data) {
                        if (null != data && null != data.getData()) {
                            String noticeContent = data.getData().getNoticeContent();
                            if (null != mTvNotice) {
                                mTvNotice.setSelected(true);
                                mTvNotice.setText(Html.fromHtml(noticeContent));
                            }
//                            BannerBean bannerBean = new BannerBean("", noticeContent, -1);
//                            mNotices.add(bannerBean);
//                            mMessageBanner.getAdapter().setDatas(mNotices);
//                            mMessageBanner.getAdapter().notifyDataSetChanged();
                        }
                    }

                });
    }

    private void initHomeBanner(List<ADBean> adBeans) {
        /**
         * 画廊效果
         */
        mHomeBanner.setAdapter(new ImageAdapter(adBeans));
        mHomeBanner.removeIndicator();
//        mHomeBanner.setIndicator(new CircleIndicator(getActivity()));
        //添加画廊效果
        mHomeBanner.setBannerGalleryEffect(10, 10);
        //(可以和其他PageTransformer组合使用，比如AlphaPageTransformer，注意但和其他带有缩放的PageTransformer会显示冲突)
        //添加透明效果(画廊配合透明效果更棒)
//        mBanner1.addPageTransformer(new AlphaPageTransformer());
        mHomeBanner.addBannerLifecycleObserver(this);
        mHomeBanner.setOnBannerListener((data, position) -> {
            if (null == data) return;
            getClickCount(((ADBean) data).getId());
            BrowserActivity.start(requireContext(), ((ADBean) data).getAdvertisingUrl());
        });
    }

    @SingleClick
    @Override
    public void onClick(View v) {
        if (!CommonHelper.isLogin()) {
            CommonHelper.goLoin();
            return;
        }
        int id = v.getId();
        if (id == R.id.ll_home_vehicle) {
            startActivity(MyVehicleManageActivity.class);
        } else if (id == R.id.ll_home_scan) {

            if (1 != CommonHelper.getCertificationStatus()) {
                toast("认证后方可操作");
                return;
            }
            //跳转的默认扫码界面
            XXPermissions.with(this)
                    // 申请单个权限
                    .permission(Permission.CAMERA)
                    // 申请多个权限
//                    .permission(Permission.Group.STORAGE)
                    // 设置权限请求拦截器（局部设置）
                    //.interceptor(new PermissionInterceptor())
                    // 设置不触发错误检测机制（局部设置）
                    //.unchecked()
                    .request(new OnPermissionCallback() {

                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            scanQRCode();
                        }

                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            if (never) {
                                toast("被永久拒绝授权，请手动授予相机权限");
                                // 如果是被永久拒绝就跳转到应用权限系统设置页面
                                XXPermissions.startPermissionActivity(requireActivity(), permissions);
                            } else {
                                toast("获取相机权限失败");
                            }
                        }
                    });
        } else if (id == R.id.me_ll_account_manage) {
            startActivity(ManageAccountActivity.class);
        } else if (id == R.id.me_ll_contact_customer) {
            PhoneUtils.dial(MTLConstants.CUSTOMER_PHONE_NUMBER);
        } else if (id == R.id.me_ll_complaint) {
            startActivity(SuggestionsActivity.class);
        } else if (id == R.id.me_ll_help_center) {
            startActivity(SuggestionsListActivity.class);
        } else if (id == R.id.tv_go_use_blank_note) {
            if (1 != CommonHelper.getCertificationStatus()) {
                toast("认证后方可操作");
                return;
            }
            startWechatApp(AppConfig.goMiniProgramHome());
        } else if (id == R.id.iv_go_oil_gas) {
            if (1 != CommonHelper.getCertificationStatus()) {
                toast("认证后方可操作");
                return;
            }
            startWechatApp(AppConfig.goMiniProgramHome());
        } else if (id == R.id.iv_go_shop_mall) {
            if (1 != CommonHelper.getCertificationStatus()) {
                toast("认证后方可操作");
                return;
            }
            startWechatApp(AppConfig.goMiniProgramShopMall());
        }
    }

    /**
     * 调用微信小程序
     */
    private void startWechatApp(String path) {
        String appId = AppConfig.getWechatAppId(); // 填移动应用(App)的 AppId，非小程序的 AppID
        IWXAPI api = WXAPIFactory.createWXAPI(requireContext(), appId);

        WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
        req.userName = AppConfig.getMiniProgramAppId(); // 填小程序原始id
        req.path = path; //拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar" "pages/productSort/productSort?memberId=1&mobile=13711111111"。
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
        api.sendReq(req);

    }

    @Permissions({Permission.CAMERA})
    private void scanQRCode() {
        startActivityForResult(ZXLCaptureActivity.class, (resultCode, data) -> {
            if (resultCode == RESULT_OK && data != null) {
                String result = CameraScan.parseScanResult(data);
                Intent intent;
                if (result == null) return;
                if (result.startsWith("HY")) {
                    intent = new Intent(requireActivity(), SourceMallDetailsActivity.class);
                } else {
                    intent = new Intent(requireActivity(), ScanOrderListActivity.class);
                }
                intent.putExtra("toNumber", result);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

}